﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Ledict.ConditionExtract.Base;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Controls;
using Ledict.Utility.Msg;
using Ledict.ConditionExtract.Model;
using System.Linq;
using System.Text;

namespace Ledict.ConditionExtract
{
    /// <summary>
    ///     表述库加工窗体
    /// </summary>
    public partial class ExpressionProcess : BaseForm
    {
        #region 构造单例
        private static ExpressionProcess _default;
        private static object _lock = new object();
        private readonly CaseCauseBLL casecausebLL = new CaseCauseBLL();
        private TreeNode clicknode;
        private string EW_IDText = "";
        private readonly ExpressGroupSituationBLL expresitu = new ExpressGroupSituationBLL();
        private string FirId = "1000";
        private string IsASC = "";
        private List<TreeNode> NodeList = new List<TreeNode>();
        private readonly string SelectText = "";

        private string sort = "";
        private readonly TreeDataBLL trbll = new TreeDataBLL();
        private string TypeName = "刑事罪名";
        private readonly Express_WordBLL wordbll = new Express_WordBLL();


        public ExpressionProcess()
        {
            InitializeComponent();
        }

        public static ExpressionProcess Default
        {
            get
            {
                if (_default == null || _default.IsDisposed)
                {
                    lock (_lock)
                    {
                        if (_default == null || _default.IsDisposed)
                        {
                            _default = new ExpressionProcess();
                        }
                    }

                }
                return _default;
            }
        }
        #endregion

        private TreeNode editnode = null;//点击获得当前节点
        readonly Express_MatchSituationBLL express_matchsituationbll = new Express_MatchSituationBLL();

        #region 鼠标单击
        private void tVCaseCause_MouseDown(object sender, MouseEventArgs e)
        {
            Point ClickPoint = new Point(e.X, e.Y);
            editnode = tVCaseCause.GetNodeAt(ClickPoint);
            if (editnode != null)//判断你点的是不是一个节点
            {
                editnode.ContextMenuStrip = contextMenuStrip1;
            }
        }
        #endregion


        private void ExpressionStorage_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            CaseCauseTree();
        }

        /// <summary>
        ///     是否有用情形
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public bool IsUseFul(TreeViewEventArgs e)
        {
            //int type = Convert.ToInt32(e.Node.Name.ToString().Split(',')[0]);
            //if (type == 4 || type == 5 || type == 6 || type == 7 || type == 8)
            //{
            return true;
            //}

            //return false;
        }

        /// <summary>
        ///     列表显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataPagerMain_PageNumberChanging(object sender, DataPagerPageIndexChangingEventArgs e)
        {
            if (clicknode != null)
            {
                var startRowIndex = e.StartRowIndex;
                //var maximumRows = e.MaximumRows;
                var endRowIndex = e.StartRowIndex + e.MaximumRows;
                var dt = new DataTable();
                var id = clicknode.Tag.ToString();

                //第一种表述节点
                //第二种原SYS_CaseCause节点
                var ismatch = IsMatch.Checked ? 1 : 0;
                var affirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";

                //id = expresitu.GetES_IDsByCCId(id, ismatch, affirmIdeaResult);
                //if (id.IndexOf("EMS") < 0)
                //{
                if (TypeName == "刑事罪名")
                {
                    if (clicknode.FullPath.IndexOf("\\单一\\") > 0)
                    {
                        id = expresitu.getES_IDsByCCId3(id, ismatch, affirmIdeaResult);
                    }
                    else
                    {
                        id = "'" + id + "'";
                    }
                }
                else if (TypeName == "民事案由")
                {
                    id = expresitu.getES_IDsByCCId4(id, affirmIdeaResult);

                }
                //}
                int isSingle = 1;
                if (clicknode.FullPath.IndexOf("\\组合\\") > 0) isSingle = 0;
                dt = wordbll.GetExpressWordData2(id);

                if (clicknode.Tag.ToString() != id.Replace('\'', ' ').Trim())
                {
                    DataTable dt2 = wordbll.GetExtraceContent(clicknode.Tag.ToString(), isSingle);
                    if (dt2 != null && dt2.Rows.Count > 0)
                    {
                        //获取两个数据源的并集
                        IEnumerable<DataRow> QBJ = dt.AsEnumerable().Union(dt2.AsEnumerable(), DataRowComparer.Default);
                        //两个数据源的并集集合
                        dt = QBJ.CopyToDataTable();
                        //dt.Merge(dt2);
                    }
                }
                DataView dv = dt.DefaultView;
                DataTable dtt = dv.ToTable(true);
                if (dtt.Rows.Count > 0)
                {
                    e.TotalCount = dtt.Rows.Count;
                    var newdt = dtt.Clone();
                    var dr = dtt.Select("showindex>" + startRowIndex + " and showindex<=" + endRowIndex);
                    for (var i = 0; i < dr.Length; i++)
                    {
                        newdt.ImportRow(dr[i]);
                    }

                    dataGridView1.DataSource = newdt;
                }
                else
                {
                    dataGridView1.DataSource = new DataTable();
                }
            }
        }

        /// <summary>
        ///     删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void delete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认要删除数据吗？", "此删除不可恢复", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    for (var i = 0; i <= dataGridView1.Rows.Count - 1; i++)
                    {
                        var check = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells["DeleteRow"];
                        if (Convert.ToBoolean(check.Value))
                        {
                            wordbll.Delete_Word(dataGridView1.Rows[i].Cells["EW_ID"].Value.ToString());
                        }
                    }
                    dataPagerMain.ChangePageNumber(1);

                    if (dataGridView1.Rows.Count == 0)
                    {
                        UpdateCC_IsShowExpress(clicknode);
                    }
                    MessageBox.Show("删除成功!");
                }
                catch (Exception error)
                {
                    MsgBox.Err("删除失败!");
                    Log.ErrorLog(error.Message);
                }
            }
        }

        /// <summary>
        ///     自己和所有父级节点记状态
        /// </summary>
        /// <param name="nowNode"></param>
        private void UpdateCC_IsShowExpress(TreeNode nowNode)
        {
            //查看节点关联的数据
            var oldid = nowNode.Tag.ToString();
            var id = "";
            var count = 0;
            if (!oldid.Contains("EMS"))
            {
                id = expresitu.GetES_IDsByCCId(oldid, 1, "1");
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText, "", 1).Rows.Count;
                id = expresitu.GetES_IDsByCCId(oldid, 1, "0");
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText, "", 1).Rows.Count;
                id = expresitu.GetES_IDsByCCId(oldid, 0, "1");
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText, "", 1).Rows.Count;
                id = expresitu.GetES_IDsByCCId(oldid, 0, "2");
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText, "", 1).Rows.Count;
            }
            else
            {
                count += wordbll.GetExractContent(id, sort, IsASC, SelectText, "", 1).Rows.Count;
            }
            //没数据且没下级
            if (nowNode.Nodes.Count == 0 && count == 0)
            {
                wordbll.UpdateCC_IsShowExpress(nowNode.Tag.ToString(), 0);
                var nowNodePid = nowNode.Parent;
                //去掉当前节点
                tVCaseCause.Nodes.Remove(nowNode);

                //递归处理父级 
                if (nowNodePid != null)
                    UpdateCC_IsShowExpress(nowNodePid);
            }
        }


        public void GetColor()
        {
            button8.BackColor = Color.White;
            button6.BackColor = Color.White;
            button5.BackColor = Color.White;
            button4.BackColor = Color.White;
            button7.BackColor = Color.White;
        }

        private void button8_Click(object sender, EventArgs e)
        {
            TypeName = "刑事罪名";
            GetColor();
            var sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            TypeName = "民事案由";
            GetColor();
            var sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            TypeName = "行政案由";
            GetColor();
            var sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            TypeName = "赔偿案由";
            GetColor();
            var sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            TypeName = "执行案由";
            GetColor();
            var sendButton = (Button)sender;
            sendButton.BackColor = Color.LightSkyBlue;
            CaseCauseTree();
        }

        private void IsMatch_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
        }

        private void NotMatch_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
        }

        private void IsAffirmIdeaResult_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
        }

        private void NotAffirmIdeaResult_Click(object sender, EventArgs e)
        {
            dataPagerMain.ChangePageNumber(1);
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 3)
            {
                EW_IDText = dataGridView1.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString();
                textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells["EW_Content"].Value.ToString();
            }
            else if (e.ColumnIndex == 6)
            {
                DataGridViewCheckBoxCell checkCellRight = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
                if (Convert.ToBoolean(checkCellRight.Value) == true)
                {
                    checkCellRight.Value = false;
                }
                else
                {
                    checkCellRight.Value = true;
                }
                EW_IDText = dataGridView1.Rows[e.RowIndex].Cells["EW_ID"].Value.ToString();
                if (Convert.ToBoolean(checkCellRight.Value))
                {

                    if (!wordbll.UpdateEW_IsAvailable(EW_IDText, 1))
                    {
                        MsgBox.Warn("修改失败！");
                    }
                }
                else
                {
                    if (!wordbll.UpdateEW_IsAvailable(EW_IDText, 0))
                    {
                        MsgBox.Warn("修改失败！");
                    }
                }

            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateWord_Click(object sender, EventArgs e)
        {
            if (wordbll.UpdateContent(EW_IDText, textBox1.Text))
            {
                MessageBox.Show("修改成功!");
            }
            else
            {
                MessageBox.Show("修改失败!");
            }
            dataPagerMain.ChangePageNumber(1);
        }

        //AboutRegexBLL aboutreg = new AboutRegexBLL();
        //ProcessDataSourceBLL datas = new ProcessDataSourceBLL();

        //WorkThread_Public work = new WorkThread_Public();
        //Express_MatchSituationBLL match = new Express_MatchSituationBLL();
        /// <summary>
        ///     各种排序
        /// </summary>
        private enum Sort
        {
            WordLengSort,
            AlphabetSort,
            CountSort,
            RightSort,
            NotChooseSort
        }

        #region 树

        StringBuilder sb = new StringBuilder();
        public void clNodes(TreeNode parentNode)
        {
            var caseTreeNodeRode = GetChild(parentNode);
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (var i = 0; i < caseTreeNodeRode.Rows.Count; i++) //下级
            {
                var node1 = new TreeNode();
                node1.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
                node1.Tag = caseTreeNodeRode.Rows[i]["id"];
                node1.Name =
                    LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"] + "," + caseTreeNodeRode.Rows[i]["TableName"]);
                if (GetChild(node1).Rows.Count > 0)
                {
                    node1.Nodes.Add(new TreeNode());
                }
                if (parentNode.Text == "组合" && node1.Nodes.Count == 0)
                {
                    continue;
                }
                parentNode.Nodes.Add(node1);
                clicknode = node1;
                if (caseTreeNodeRode.Rows[i]["CC_NodeType"].ToString() == "4" || caseTreeNodeRode.Rows[i]["CC_NodeType"].ToString() == "5" || caseTreeNodeRode.Rows[i]["CC_NodeType"].ToString() == "6")
                {
                    if (clicknode != null)
                    {
                        var dt = new DataTable();
                        var id = node1.Tag.ToString();
                        //第一种表述节点
                        //第二种原SYS_CaseCause节点
                        var ismatch = IsMatch.Checked ? 1 : 0;
                        var affirmIdeaResult = IsAffirmIdeaResult.Checked ? "1" : "2";
                        string id1 = string.Empty;
                        if (TypeName == "刑事罪名")
                        {
                            id1 = expresitu.getES_IDsByCCId3(id, ismatch, affirmIdeaResult);
                            if (!string.IsNullOrEmpty(id1))
                            {
                                id = id1;
                            }
                            else
                            {
                                id = "'" + id + "'";
                            }
                        }

                        //}
                        int isSingle = 1;
                        if (string.IsNullOrEmpty(id1)) isSingle = 0;
                        dt = wordbll.GetExpressWordData2(id);

                        if (clicknode.Tag.ToString() != id.Replace('\'',' ').Trim())
                        {
                            DataTable dt2 = wordbll.GetExtraceContent(clicknode.Tag.ToString(), isSingle);
                            if (dt2 != null && dt2.Rows.Count > 0)
                            {
                                //获取两个数据源的并集
                                IEnumerable<DataRow> QBJ = dt.AsEnumerable().Union(dt2.AsEnumerable(), DataRowComparer.Default);
                                //两个数据源的并集集合
                                dt = QBJ.CopyToDataTable();
                                //dt.Merge(dt2);
                            }
                        }

                        if (dt != null && dt.Rows.Count > 0 && dt.Select(" EW_IsAvailable=1 ").Length == 0)
                        {
                            DataRow dr = dt.Rows.OfType<DataRow>().OrderByDescending(x => x.Field<Int32>("EW_UseCount")).FirstOrDefault();
                            EW_IDText = dr["EW_ID"].ToString();
                            bool res1 = wordbll.UpdateEW_IsAvailable(EW_IDText, 1);
                        }
                        else
                        {
                            if (node1.Text != "组合" && node1.Text != "单一")
                            {
                                sb.Append(node1.Tag + ",");
                            }
                        }
                    }
                }
                clNodes(node1);
            }
        }

        public void CaseCauseTree()
        {
            #region 初始化

            tVCaseCause.Nodes.Clear();
            NodeList = new List<TreeNode>();

            StacticQuery.Text = "";
            CurrNodeNum.Text = "";
            SumQuery.Text = "";

            #endregion

            //var nodes = trbll.GetCauseTree_Two("", 1).Select("name='刑事罪名'");
            //foreach (var caseTreeNodeRode in nodes)
            //{
            //    var node = new TreeNode();
            //    node.Text = LdFormat.ObjectToString(caseTreeNodeRode["name"]);
            //    node.Tag = caseTreeNodeRode["id"];
            //    node.Name =
            //        LdFormat.ObjectToString(caseTreeNodeRode["CC_NodeType"] + "," + caseTreeNodeRode["TableName"]);
            //    clNodes(node);
            //}

            var dt = trbll.GetCauseTree_Two("", 1); // 第一层
            if (dt.Rows.Count > 0)
            {
                var arrayDr = dt.Select("name='" + TypeName + "'");

                foreach (var caseTreeNodeRode in arrayDr)
                {
                    var node = new TreeNode();
                    node.Text = LdFormat.ObjectToString(caseTreeNodeRode["name"]);
                    node.Tag = caseTreeNodeRode["id"];
                    node.Name =
                        LdFormat.ObjectToString(caseTreeNodeRode["CC_NodeType"] + "," + caseTreeNodeRode["TableName"]);
                    FirId = caseTreeNodeRode[0].ToString();
                    if (trbll.GetCauseTree_Two(node.Tag.ToString(), 1).Rows.Count > 0) //第二层
                    {
                        node.Nodes.Add(new TreeNode());
                    }
                    tVCaseCause.Nodes.Add(node);
                    NodeList.Add(node);
                }
            }
        }

        /// <summary>
        ///     显示下一级树节点
        /// </summary>
        /// <param name="parentNode"></param>
        private void CaseCauseTreeChild(TreeNode parentNode)
        {
            var caseTreeNodeRode = new DataTable();
            if (TypeName == "民事案由")
            {
                caseTreeNodeRode = GetChild1(parentNode);
            }
            else
            {
                caseTreeNodeRode = GetChild(parentNode);
            }
            if (caseTreeNodeRode.Rows.Count == 0)
                return;
            for (var i = 0; i < caseTreeNodeRode.Rows.Count; i++) //下级
            {
                var node = new TreeNode();
                node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
                node.Tag = caseTreeNodeRode.Rows[i]["id"];
                node.Name =
                    LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"] + "," +
                                            caseTreeNodeRode.Rows[i]["TableName"]);
                if (TypeName == "民事案由")
                {
                    if (GetChild1(node).Rows.Count > 0)
                    {
                        node.Nodes.Add(new TreeNode());
                    }
                }
                else
                {
                    if (GetChild(node).Rows.Count > 0)
                    {
                        node.Nodes.Add(new TreeNode());
                    }
                }
                //if (parentNode.Text == "组合" && node.Nodes.Count == 0)
                //    continue;
                parentNode.Nodes.Add(node);
                NodeList.Add(node);
            }
        }


        /// <summary>
        /// 获取下一级树节点
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <returns></returns>
        private DataTable GetChild1(TreeNode parentNode)
        {
            var pid = parentNode.Tag.ToString();
            DataTable caseTreeNodeRode;
            //var name = parentNode.Name.Split(',');
            //var ptype = Convert.ToInt32(name[0]);
            //parentNode.Text == "单一" ||
            if (parentNode.Text == "组合" || pid.StartsWith("EMS"))
            {
                DataTable dt = express_matchsituationbll.GetExpressNodeData1(pid);
                if (dt != null && dt.Rows.Count > 0)
                {
                    return dt;
                }
                else
                {
                    return new DataTable();
                }
            }
            if (parentNode.Text == "单一")
            {
                SYS_Express_MatchSituation sem = express_matchsituationbll.GetMatchSituation(pid);
                pid = sem.ParentID.ToString();
            }
            SYS_CaseCause scc = casecausebLL.GetCaseCauseByCCID(pid);
            if (scc.AllParentName.Contains("民间借贷纠纷") && scc.AllParentName.Contains("争议焦点要素"))
            {
                var name = parentNode.Name.Split(',');
                var ptype = Convert.ToInt32(name[0]);
                //16争议焦点 17裁判理由
                if (ptype == 16)
                {
                    DataTable dt = express_matchsituationbll.GetExpressNodeData1(pid);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        return dt;
                    }
                    else
                    {
                        caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 1);
                        return caseTreeNodeRode;
                    }
                }
                else if (ptype == 17 )
                {
                    return new DataTable();
                }
                else
                {
                    caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 1);
                    return caseTreeNodeRode;
                }
            }
            else if (scc.AllParentName.Contains("民间借贷纠纷") && scc.AllParentName.Contains("理由要素"))
            {
                var name = parentNode.Name.Split(',');
                var ptype = Convert.ToInt32(name[0]);
                //22裁判结果
                if (ptype == 22)
                {
                    DataTable dt = express_matchsituationbll.GetExpressNodeData1(pid);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        return dt;
                    }
                    else
                    {
                        caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 1);
                        return caseTreeNodeRode;
                    }
                }
                else if (ptype == 17)
                {
                    return new DataTable();
                }
                else
                {
                    caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 1);
                    return caseTreeNodeRode;
                }
            }

            else
            {
                caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 1);
                return caseTreeNodeRode;
            }
        }

        /// <summary>
        ///     获取下一级树节点
        /// </summary>
        /// <param name="parentNode">父节点</param>
        /// <returns></returns>
        private DataTable GetChild(TreeNode parentNode)
        {
            var pid = parentNode.Tag.ToString();
            var pName = parentNode.Text;

            var name = parentNode.Name.Split(',');
            var ptype = Convert.ToInt32(name[0]);
            var tableName = Convert.ToInt32(name[1]);
            var childType = trbll.GetChildType(pid, ptype, tableName);
            //下级改去哪个表查0：CaseCause 1:SYS_Express_GroupSituation
            DataTable caseTreeNodeRode;
            if (childType == 1)
            {
                if (tableName == 0) //如果是第一级 找组合单一
                {
                    var ccIsCombination = 0;
                    var model = casecausebLL.GetCaseCauseByCCID(pid);
                    if (model != null && model.CC_IsCombination == 1)
                        ccIsCombination = 1;
                    caseTreeNodeRode = trbll.GetCauseTreeThree_ToExpressTab_Virtual(pid, ccIsCombination);
                }
                else
                {
                    if (pName == "组合") //如果是组合的，去前缀
                        pid = pid.Substring(1, pid.Length - 1);
                    caseTreeNodeRode = trbll.GetCauseTreeTwo_ToExpressTab(pid, 1); //SYS_Express_GroupSituation 
                }
            }
            else
            {
                if (pName == "单一") //如果是单一，去前缀
                    pid = pid.Substring(1, pid.Length - 1);
                caseTreeNodeRode = trbll.GetCauseTree_Two(pid, 1); //CaseCause
            }
            return caseTreeNodeRode;
        }

        private void tVCaseCause_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();

            CaseCauseTreeChild(e.Node);
        }

        /// <summary>
        ///     选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tVCaseCause_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //if (IsUseFul(e))
            //{
                if (clicknode != null)
                {
                    clicknode.ForeColor = Color.Black;
                }
                clicknode = e.Node;

                clicknode.ForeColor = Color.Red;

                dataPagerMain.ChangePageNumber(1);
            //}
        }

        #endregion

        #region 各种排序

        private void WordLengSort_Click(object sender, EventArgs e)
        {
            sort = "WordLengSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void AlphabetSort_Click(object sender, EventArgs e)
        {
            sort = "AlphabetSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        private void CountSort_Click(object sender, EventArgs e)
        {
            sort = "CountSort";
            if (IsASC == "")
            {
                IsASC = "desc";
            }
            else
            {
                IsASC = "";
            }
            dataPagerMain.ChangePageNumber(1);
        }

        #endregion

        #region 查询节点

        private DataTable Querydt;

        private void QueryNodeTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                QueryNode();
            }
        }

        private void QueryNode()
        {
            var queryNodeName = QueryNodeTxt.Text.Trim();

            if (queryNodeName != "")
            {
                Querydt = trbll.NodeTree_Query(FirId, queryNodeName, 2);
                StacticQuery.Text = Querydt.Rows.Count.ToString();
                if (Querydt.Rows.Count > 0)
                {
                    CurrNodeNum.Text = "1";
                    SumQuery.Text = CurrNodeNum.Text;
                    var currNode = Convert.ToInt32(CurrNodeNum.Text);
                    LinkIsVisible(currNode);
                    QueryNode_Page(Querydt, currNode);
                }
                else
                {
                    CurrNodeNum.Text = "0";
                    SumQuery.Text = CurrNodeNum.Text;
                    MessageBox.Show("没有查询到结果！");
                }
            }
            else
            {
                MessageBox.Show("请输入关键字！");
            }
        }


        private void QueryNodeBtn_Click(object sender, EventArgs e) //查询
        {
            QueryNode();
        }

        /// <summary>
        ///     下一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Nextlinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (CurrNodeNum.Text != "")
            {
                CurrNodeNum.Text = (Convert.ToInt32(CurrNodeNum.Text) + 1).ToString();
                SumQuery.Text = CurrNodeNum.Text;
                var currNode = Convert.ToInt32(CurrNodeNum.Text);
                QueryNode_Page(Querydt, currNode);
                LinkIsVisible(currNode);
            }
        }

        /// <summary>
        ///     上一条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Prelinkbtn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (CurrNodeNum.Text != "")
            {
                CurrNodeNum.Text = (Convert.ToInt32(CurrNodeNum.Text) - 1).ToString();
                SumQuery.Text = CurrNodeNum.Text;
                var currNode = Convert.ToInt32(CurrNodeNum.Text);
                QueryNode_Page(Querydt, currNode);
                LinkIsVisible(currNode);
            }
        }

        /// <summary>
        ///     查询分页
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="showindex"></param>
        private void QueryNode_Page(DataTable dt, int showindex)
        {
            if (dt.Rows.Count >= showindex)
            {
                var notePidArr = trbll.GetAllParentNode(dt.Rows[showindex - 1]["id"].ToString()).Split(',');
                for (var i = 0; i < notePidArr.Length; i++)
                {
                    if (i != notePidArr.Length - 1)
                    {
                        TreeNode tn = FindNode(notePidArr[i]);
                        if (tn != null)
                        {
                            tn.Expand();
                        }
                    }
                    else
                    {
                        var node = FindNode(notePidArr[i]);
                        tVCaseCause.SelectedNode = node;
                    }
                }
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }
        }

        /// <summary>
        ///     找到节点
        /// </summary>
        /// <param name="Nodeid"></param>
        /// <returns></returns>
        private TreeNode FindNode(string Nodeid)
        {
            foreach (var node in NodeList)
            {
                if (node.Tag.ToString() == Nodeid)
                {
                    return node;
                }
            }
            return null;
        }

        /// <summary>
        ///     上一条下一条是否可用
        /// </summary>
        /// <param name="currNode"></param>
        private void LinkIsVisible(int currNode)
        {
            Prelinkbtn.Enabled = true;
            Nextlinkbtn.Enabled = true;
            if (currNode <= 1)
            {
                Prelinkbtn.Enabled = false;
            }
            if (currNode >= Querydt.Rows.Count)
            {
                Nextlinkbtn.Enabled = false;
            }
        }

        /// <summary>
        ///     跳页查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GoQuery_Click(object sender, EventArgs e)
        {
            var currNode = Convert.ToInt32(SumQuery.Text);

            if (Querydt.Rows.Count >= currNode)
            {
                CurrNodeNum.Text = SumQuery.Text;
                QueryNode_Page(Querydt, currNode);
                LinkIsVisible(currNode);
            }
            else
            {
                MessageBox.Show("跳转页码有误，重新输入！");
            }
        }

        #endregion

        #region 全部展开
        private void 全部展开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AllExpandNode(editnode.Tag.ToString());//展开全部
        }

        /// <summary>
        /// 展开全部
        /// </summary>
        /// <param name="pid"></param>
        private void AllExpandNode(string pid)
        {

            var findNode = FindNode(pid);
            if (findNode != null) findNode.ExpandAll();

            //DataTable caseTreeNodeRode = trbll.NodeTree_Tree(pid);//父级ID的下级节点
            //if (caseTreeNodeRode.Rows.Count == 0)
            //    return;
            //for (int i = 0; i < caseTreeNodeRode.Rows.Count; i++)
            //{
            //    TreeNode node = new TreeNode();
            //    node.Text = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["name"]);
            //    node.Tag = caseTreeNodeRode.Rows[i]["id"];
            //    node.Name = LdFormat.ObjectToString(caseTreeNodeRode.Rows[i]["CC_NodeType"]);
            //    AllExpandNode(node.Tag.ToString());
            //}
        }

        #endregion

        private void button2_Click(object sender, EventArgs e)
        {

        }
    }
}